import React from 'react';
import { Button, Tooltip } from 'antd';
import type { ButtonProps } from 'antd/es/button';
import type { TooltipProps } from 'antd/es/tooltip';

export interface LoadingButtonProps extends Omit<ButtonProps, 'loading'> {
  /** 加载状态 */
  loading?: boolean;
  /** Tooltip 提示文本 */
  tooltip?: string;
  /** Tooltip 配置 */
  tooltipProps?: Omit<TooltipProps, 'title' | 'children'>;
  /** 防止重复点击的延迟时间（毫秒） */
  debounceMs?: number;
  /** 点击处理函数 */
  onClick?: (e: React.MouseEvent<HTMLElement>) => void | Promise<void>;
}

const LoadingButton: React.FC<LoadingButtonProps> = ({
  loading = false,
  tooltip,
  tooltipProps,
  debounceMs = 0,
  onClick,
  disabled,
  children,
  ...buttonProps
}) => {
  const [isDebouncing, setIsDebouncing] = React.useState(false);
  const isDisabled = disabled || loading || isDebouncing;

  const handleClick = async (e: React.MouseEvent<HTMLElement>) => {
    if (isDisabled) {
      return;
    }

    // 如果有防抖延迟，设置防抖状态
    if (debounceMs > 0) {
      setIsDebouncing(true);
      setTimeout(() => {
        setIsDebouncing(false);
      }, debounceMs);
    }

    // 处理点击事件
    if (onClick) {
      try {
        await onClick(e);
      } catch (error) {
        // 如果点击事件抛出异常，清除防抖状态
        setIsDebouncing(false);
        throw error;
      }
    }
  };

  const button = (
    <Button
      {...buttonProps}
      loading={loading}
      disabled={isDisabled}
      onClick={handleClick}
    >
      {children}
    </Button>
  );

  // 如果有tooltip，则包装在Tooltip中
  if (tooltip) {
    return (
      <Tooltip title={tooltip} {...tooltipProps}>
        {button}
      </Tooltip>
    );
  }

  return button;
};

export default LoadingButton;